/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved. distributed with this file and
 * available online at
 */
package com.lap.auth.adapter.driving.persistence.project.repository;

import com.lap.auth.adapter.driving.persistence.project.ProjectConverter;
import com.lap.auth.adapter.driving.persistence.project.mapper.ProjectMapper;
import com.lap.auth.adapter.driving.persistence.project.po.ProjectPo;
import com.lap.auth.domain.project.Project;
import com.lap.auth.domain.project.repository.ProjectRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class ProjectRepositoryImpl implements ProjectRepository {

  private final ProjectConverter converter;
  private final ProjectMapper projectMapper;

  @Override
  public Integer save(Project project) {
    ProjectPo projectPo = converter.toPo(project);
    if (project.isNew()) {
      projectMapper.insert(projectPo);
      return projectPo.getId();
    }
    return projectMapper.updateById(projectPo);
  }

  @Override
  public int deleteById(Integer id) {
    return projectMapper.deleteById(id);
  }

  @Override
  public Optional<Project> findById(Integer id) {
    var projectPo = projectMapper.selectById(id);
    return Optional.ofNullable(converter.toDomain(projectPo));
  }

  @Override
  public Optional<Project> findByContext(String context) {
    var projectPo = projectMapper.selectByContext(context);
    return Optional.ofNullable(converter.toDomain(projectPo));
  }
}
